package _1_常用数据类型_关键字;

import _0_object_oriented.OtherField;
import _0_object_oriented.User;
import org.junit.Assert;
import org.junit.Test;

import java.util.Optional;

/**
 * Created by bpzj on 9/13/2018.
 */
public class OptionalAndNull {

    @Test
    public void optionalDemo() {
        User user = new User();
        // 无 Optional 给null值重新赋值:
        String name = user.getName();
        if (name == null) {
            name = "who";
        }
        // 有 Optional, 使用 orElse, orElseGet
        String userName = Optional.ofNullable(user.getName()).orElse("");


        // 无 Optional 多次 空指针判断：
        OtherField otherField = user.getOtherField();
        String favoriteGirl = null;
        if (otherField != null) {
            favoriteGirl = otherField.getFavoriteGirl();
            if (favoriteGirl != null) {
                favoriteGirl = "who";
            }
        } else {
            favoriteGirl = "who";
        }


        // 使用 _2_lambda 表达式 链式调用，避免空指针判断
        Optional<User> userOptional = Optional.of(user);
        String favoriteGirl1 = userOptional
            .map(User::getOtherField)
            .map(OtherField::getFavoriteGirl)
            .orElse("who");

        Assert.assertEquals(favoriteGirl1, favoriteGirl);
    }

    @Test
    public void nullTest() {
        String a = null;
        System.out.println(a != null);
    }

}
